package com.lnsoft.cac.server.handle.codec.frameMessage;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.NonNull;

@Data
/**
 * 数据请求
 * */
public class ReqData_Cfm {
    private int Measure_Point_ID;               //1byte         监测点号（无符号整数）
    private int Request_Type;                   //1byte         请求数据类型—参考表A.2.8相关含义
    private int Data_Start_Time;                //4byte         请求分钟平均值的开始时间（世纪秒，解析到分钟）
    private int Data_End_Time;                  //4byte         请求分钟平均值的结束时间（世纪秒，解析到分钟）
    private int Command_Status;                 //1byte         数据发送状态：①0xFF成功②0x00失败


    public ByteBuf toByteBuf() throws Exception{
        if (!Util.measurePointIDIsAvailable(Measure_Point_ID)) {
            throw new Exception("监测点号 设置异常");
        }
        if (Command_Status != (byte)0xFF && Command_Status != (byte)0x00) {
            throw new Exception("数据发送状态 设置异常");
        }
        ByteBuf bf = Unpooled.buffer(11);
        bf.writeByte(Measure_Point_ID);
        bf.writeByte(Request_Type);
        bf.writeIntLE(Data_Start_Time);
        bf.writeIntLE(Data_End_Time);
        bf.writeByte(Command_Status);
        return bf;
    }


    //  解析 [数据请求-确认] 帧报文内容区 到消息体中
    public static ReqData_Cfm decFrameBody(@NonNull byte[] frameBody) throws Exception {
        ByteBuf bf = Unpooled.wrappedBuffer(frameBody);
        ReqData_Cfm msg = new ReqData_Cfm();
        int len = frameBody.length;
        if (len == 0) {
            return null;
        }
        if (11 != len) {
            throw new Exception("frameBody 数据异常");
        }
        msg.setMeasure_Point_ID(bf.getUnsignedByte(0));
        msg.setRequest_Type(bf.getByte(1) & 0xFF);
        msg.setData_Start_Time(bf.getIntLE(2) & 0xFFFFFFFF);
        msg.setData_Start_Time(bf.getIntLE(6) & 0xFFFFFFFF);
        msg.setCommand_Status(bf.getUnsignedByte(10));
        return msg;
    }
}
